import { nutritionPerGram } from '../../utils/mockData.js'

Page({
  data: {
    imageUrl: '',
    imageSource: '', // camera | album
    ocrLoading: false,
    ocrError: '',
    items: [], // [{name, weight, calories, protein, fat, carbs, sodium}]
    summary: {
      totalCalories: 0,
      totalProtein: 0,
      totalFat: 0,
      totalCarbs: 0,
      totalSodium: 0
    },
    advice: [] // [{level: 'warn'|'info'|'ok', text}]
  },

  onPickImage() {
    const that = this
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success(res) {
        if (res.tapIndex === 0) {
          that.chooseImage('camera')
        } else if (res.tapIndex === 1) {
          that.chooseImage('album')
        }
      }
    })
  },

  chooseImage(sourceType) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [sourceType],
      success(res) {
        const filePath = res.tempFilePaths[0]
        that.setData({ imageUrl: filePath, imageSource: sourceType, ocrError: '', items: [], summary: that._initSummary(), advice: [] })
      }
    })
  },

  onRePick() {
    this.onPickImage()
  },

  onRunOCR() {
    if (!this.data.imageUrl) return
    this.setData({ ocrLoading: true, ocrError: '' })

    // 模拟 OCR + 分类 + 分量估算
    setTimeout(() => {
      try {
        const items = this._mockOcrParse(this.data.imageUrl)
        const enriched = items.map(this._estimateNutrition)
        const summary = this._calcSummary(enriched)
        const advice = this._generateAdvice(summary, enriched)
        this.setData({ items: enriched, summary, advice, ocrLoading: false })
      } catch (e) {
        this.setData({ ocrLoading: false, ocrError: '识别失败，请重试' })
      }
    }, 1000)
  },

  _mockOcrParse(filePath) {
    // 根据文件名简单决定场景：ticket（小票）/ package（包装）/ dish（菜品）
    const lower = (filePath || '').toLowerCase()
    if (lower.includes('ticket') || lower.includes('receipt')) {
      return [
        { name: '米饭', weight: 200 },
        { name: '红烧肉', weight: 150 },
        { name: '清炒西兰花', weight: 120 }
      ]
    }
    if (lower.includes('package') || lower.includes('nutrition')) {
      return [
        { name: '酸奶', weight: 200 },
        { name: '燕麦片', weight: 40 }
      ]
    }
    // 默认菜品图
    return [
      { name: '番茄炒蛋', weight: 250 },
      { name: '烧茄子', weight: 180 }
    ]
  },

  _estimateNutrition(item) {
    // 1) 优先使用 nutritionPerGram（单位：每克含量），根据重量(g)直接乘
    const per = nutritionPerGram[item.name]
    if (per) {
      const grams = item.weight
      // 简易热量估算：4 kcal/g 蛋白 + 9 kcal/g 脂肪 + 4 kcal/g 碳水
      const calories = Math.round(per.protein * grams * 4 + per.fat * grams * 9 + per.carbs * grams * 4)
      return {
        ...item,
        calories,
        protein: Math.round(per.protein * grams),
        fat: Math.round(per.fat * grams),
        carbs: Math.round(per.carbs * grams),
        sodium: 0 // 无钠数据时置0，可后续补充
      }
    }

    // 2) 回退到原有内置估算表（单位每100g）
    const table = {
      '米饭': { kcal: 116, p: 2.6, f: 0.3, c: 25.9, na: 2 },
      '红烧肉': { kcal: 350, p: 13, f: 30, c: 4, na: 500 },
      '清炒西兰花': { kcal: 55, p: 3.7, f: 2.6, c: 5.2, na: 30 },
      '番茄炒蛋': { kcal: 110, p: 6.5, f: 7.5, c: 4, na: 180 },
      '烧茄子': { kcal: 150, p: 2, f: 12, c: 9, na: 250 },
      '酸奶': { kcal: 72, p: 3.3, f: 3.5, c: 5, na: 50 },
      '燕麦片': { kcal: 380, p: 13, f: 7, c: 68, na: 5 }
    }
    const ref = table[item.name] || { kcal: 120, p: 4, f: 4, c: 18, na: 50 }
    const ratio = item.weight / 100
    return {
      ...item,
      calories: Math.round(ref.kcal * ratio),
      protein: Math.round(ref.p * ratio),
      fat: Math.round(ref.f * ratio),
      carbs: Math.round(ref.c * ratio),
      sodium: Math.round(ref.na * ratio)
    }
  },

  _calcSummary(items) {
    const s = this._initSummary()
    items.forEach((it) => {
      s.totalCalories += it.calories
      s.totalProtein += it.protein
      s.totalFat += it.fat
      s.totalCarbs += it.carbs
      s.totalSodium += it.sodium
    })
    return s
  },

  _initSummary() {
    return { totalCalories: 0, totalProtein: 0, totalFat: 0, totalCarbs: 0, totalSodium: 0 }
  },

  _generateAdvice(summary, items) {
    // 简单规则：热量>800 警告；脂肪高提醒；蛋白不足提示加蛋白质；钠过高少盐
    const adv = []
    if (summary.totalCalories > 800) {
      adv.push({ level: 'warn', text: '当餐热量偏高，适当减少主食/油脂摄入' })
    } else if (summary.totalCalories < 400) {
      adv.push({ level: 'info', text: '当餐热量较低，可适量补充优质碳水' })
    }
    if (summary.totalFat > 35) {
      adv.push({ level: 'warn', text: '脂肪偏高，建议少油烹饪或更换为清淡菜式' })
    }
    if (summary.totalProtein < 20) {
      adv.push({ level: 'info', text: '蛋白质略低，可增加瘦肉/鱼/蛋/豆制品' })
    }
    if (summary.totalSodium > 1500) {
      adv.push({ level: 'warn', text: '钠摄入较高，建议少盐少酱油，注意高钠食物' })
    }
    // 针对具体菜品的替换建议（示例）
    const hasHongShaorou = items.some(i => i.name === '红烧肉')
    if (hasHongShaorou) {
      adv.push({ level: 'info', text: '可将红烧肉部分替换为白切鸡/清蒸鱼以降脂' })
    }
    return adv
  },

  onSaveRecord() {
    if (!this.data.items.length) return
    const record = {
      ts: Date.now(),
      items: this.data.items,
      summary: this.data.summary
    }
    try {
      const list = wx.getStorageSync('ocr_records') || []
      list.unshift(record)
      wx.setStorageSync('ocr_records', list)
      wx.showToast({ title: '已保存', icon: 'success' })
    } catch (e) {
      wx.showToast({ title: '保存失败', icon: 'none' })
    }
  }
})